package com.association.main.controller;

import com.association.main.common.R;
import com.association.main.domain.*;
import com.association.main.service.*;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/statistics")
public class StatisticsController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private MembersService membersService;
    @Autowired
    private JoinInfoService joinInfoService;


    @Autowired
    private ClubsService clubsService;

    @Autowired
    private NotificationsService notificationsService;

    @Autowired
    private EventsService eventsService;

    @Autowired
    private VoteService voteService;

    @Autowired
    private ApplyJoinService applyJoinService;

    @GetMapping("/user")
    public R<Map<String, Object>> userStatistics() {
        LambdaQueryWrapper<Users> usersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        usersLambdaQueryWrapper.eq(Users::getRole, "admin");
        int adminCount = usersService.count(usersLambdaQueryWrapper);

        int sumCount = usersService.count();
        int adminMemCount = sumCount - adminCount;

        int memberSum = membersService.count();
        LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        joinInfoLambdaQueryWrapper.select(JoinInfo::getMemberId).groupBy(JoinInfo::getMemberId);
        List<JoinInfo> list = joinInfoService.list(joinInfoLambdaQueryWrapper);

        Set<Integer> distinctMemberIds = new HashSet<>();
        for (JoinInfo joinInfo : list) {
            distinctMemberIds.add(joinInfo.getMemberId());
        }

        int joinSum = distinctMemberIds.size();

        int simplySum = memberSum - joinSum;

        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> simplyUser = new HashMap<>();
        simplyUser.put("value", simplySum);
        simplyUser.put("name", "普通用户");
        dataList.add(simplyUser);

        Map<String, Object> joinUser = new HashMap<>();
        joinUser.put("value", joinSum);
        joinUser.put("name", "社团成员用户");
        dataList.add(joinUser);

        Map<String, Object> adminMemUser = new HashMap<>();
        adminMemUser.put("value", adminMemCount);
        adminMemUser.put("name", "社团管理员");
        dataList.add(adminMemUser);

        Map<String, Object> adminUser = new HashMap<>();
        adminUser.put("value", adminCount);
        adminUser.put("name", "系统管理员");
        dataList.add(adminUser);

        Map<String, Object> userCount = new HashMap<>();
        userCount.put("data", dataList);

        return R.success(userCount);
    }
    @GetMapping("/club")
    public R<Map> clubStatistics(HttpServletRequest request) {
        // 统计社团的成员总数
        // 1. 查询所有社团
        String token = request.getHeader("token");
        String userType = JwtUtil.getUserType(token);
        List<Clubs> list=new ArrayList<>();
        if(userType.equals("member")){
            Integer userId = JwtUtil.getUserId(token);
            LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper=new LambdaQueryWrapper<>();
            clubsLambdaQueryWrapper.eq(Clubs::getCreatedBy,userId);
             list = clubsService.list(clubsLambdaQueryWrapper);
        }else{
             list = clubsService.list();
        }

        Map<String, Object> clubMsgCount = new HashMap<>();

        List<String> clubNames = new ArrayList<>();
        List<Long> jCount = new ArrayList<>();
        List<Long> nCount = new ArrayList<>();
        List<Long> vCount = new ArrayList<>();
        List<Long> eCount = new ArrayList<>();

        list.forEach(clubs -> {
            LambdaQueryWrapper<JoinInfo> joinInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<Notifications> notificationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<Events> eventsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<Vote> voteLambdaQueryWrapper = new LambdaQueryWrapper<>();

            joinInfoLambdaQueryWrapper.eq(JoinInfo::getClubId, clubs.getId());
            notificationsLambdaQueryWrapper.eq(Notifications::getClubId, clubs.getId());
            eventsLambdaQueryWrapper.eq(Events::getClubId, clubs.getId());
            voteLambdaQueryWrapper.eq(Vote::getClubId, clubs.getId());

            int notificationCount = notificationsService.count(notificationsLambdaQueryWrapper); // 统计社团发布的通知个数
            int eventCount = eventsService.count(eventsLambdaQueryWrapper); // 统计社团发布的活动个数
            int voteCount = voteService.count(voteLambdaQueryWrapper); // 统计社团发布的投票个数
            int joinCount = joinInfoService.count(joinInfoLambdaQueryWrapper); // 统计社团的成员总数

            // 将统计结果放入相应的列表中
            clubNames.add(clubs.getName());
            jCount.add((long) joinCount);
            nCount.add((long) notificationCount);
            vCount.add((long) voteCount);
            eCount.add((long) eventCount);
        });

        clubMsgCount.put("clubNames", clubNames);
        clubMsgCount.put("joinCount", jCount);
        clubMsgCount.put("notificationCount", nCount);
        clubMsgCount.put("voteCount", vCount);
        clubMsgCount.put("eventCount", eCount);

        return R.success(clubMsgCount);
    }

    @GetMapping("/event")
    public R<Map<String, Object>> eventStatistics() {
        LocalDateTime now = LocalDateTime.now(); // 获取当前时间

        LambdaQueryWrapper<Events> eventsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Map<String, Object>> dataList = new ArrayList<>();

        // 查询正在举办中的公共活动数量
        eventsLambdaQueryWrapper.eq(Events::getTurnUser, true)
                .le(Events::getStartTime, now)
                .ge(Events::getEndTime, now);
        int ongoingPublicEventsCount = eventsService.count(eventsLambdaQueryWrapper);

        Map<String, Object> publicEvent = new HashMap<>();
        publicEvent.put("value", ongoingPublicEventsCount);
        publicEvent.put("name", "举办中公共活动");
        dataList.add(publicEvent);

        // 查询正在举办中的社团活动数量
        eventsLambdaQueryWrapper.clear(); // 清空查询条件
        eventsLambdaQueryWrapper.eq(Events::getTurnUser, false)
                .le(Events::getStartTime, now)
                .ge(Events::getEndTime, now);
        int ongoingClubEventsCount = eventsService.count(eventsLambdaQueryWrapper);

        Map<String, Object> clubEvent = new HashMap<>();
        clubEvent.put("value", ongoingClubEventsCount);
        clubEvent.put("name", "举办中社团活动");
        dataList.add(clubEvent);

        // 查询已完成活动数量
        eventsLambdaQueryWrapper.clear(); // 清空查询条件
        eventsLambdaQueryWrapper.le(Events::getEndTime, now);
        int completedEventsCount = eventsService.count(eventsLambdaQueryWrapper);

        Map<String, Object> completedEvent = new HashMap<>();
        completedEvent.put("value", completedEventsCount);
        completedEvent.put("name", "已完成活动");
        dataList.add(completedEvent);

        // 查询未开始活动数量
        eventsLambdaQueryWrapper.clear(); // 清空查询条件
        eventsLambdaQueryWrapper.ge(Events::getStartTime, now);
        int upcomingEventsCount = eventsService.count(eventsLambdaQueryWrapper);

        Map<String, Object> upcomingEvent = new HashMap<>();
        upcomingEvent.put("value", upcomingEventsCount);
        upcomingEvent.put("name", "未开始活动");
        dataList.add(upcomingEvent);

        Map<String, Object> eventCount = new HashMap<>();
        eventCount.put("data", dataList);

        return R.success(eventCount);
    }

    @GetMapping("/apply")
    public R<List> applyStatistics(HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        clubsLambdaQueryWrapper.eq(Clubs::getCreatedBy,userId);
        List<Clubs> list = clubsService.list(clubsLambdaQueryWrapper);
        List<Map<String, Object>> dataList = new ArrayList<>();
        AtomicInteger applyCount = new AtomicInteger(0);
        AtomicInteger applyCount2 = new AtomicInteger(0);
        list.forEach(clubs -> {

            LambdaQueryWrapper<ApplyJoin> applyJoinLambdaQueryWrapper = new LambdaQueryWrapper<>();
            applyJoinLambdaQueryWrapper.eq(ApplyJoin::getClubId, clubs.getId());
            applyCount2.addAndGet(applyJoinService.count(applyJoinLambdaQueryWrapper));
            applyJoinLambdaQueryWrapper.eq(ApplyJoin::getStatus, 0);
            applyCount.addAndGet(applyJoinService.count(applyJoinLambdaQueryWrapper));
        });

        Map<String, Object> applyOne = new HashMap<>();
        applyOne.put("value", applyCount.get());
        applyOne.put("name", "待审核入团记录");
        dataList.add(applyOne);
        Map<String, Object> applyTwo = new HashMap<>();
        applyTwo.put("value", applyCount2.get()-applyCount.get());
        applyTwo.put("name", "已审核入团记录");
        dataList.add(applyTwo);


        return R.success(dataList);
    }
}
